package com.kidback.bbloc259.ui;

import android.view.View;
import android.view.ViewGroup;

import com.alipay.sdk.app.PayTask;
import com.kidback.bbloc259.api.BBNetApi;
import com.kidback.bbloc259.app.KidApplication;
import com.kidback.bbloc259.app.provider.UserDataProvider;
import com.kidback.bbloc259.base.BaseFragment;
import com.kidback.bbloc259.databinding.MineFragmentBinding;
import com.kidback.bbloc259.event.UserInfoEvent;
import com.kidback.bbloc259.network.base.ApiHelper;
import com.kidback.bbloc259.network.beans.BaseResponse;
import com.kidback.bbloc259.network.errorhandler.ResponseThrowable;
import com.kidback.bbloc259.network.observer.BaseObserver;
import com.kidback.bbloc259.ui.account.LoginActivity;
import com.kidback.bbloc259.ui.home.AddFriendDialog;
import com.kidback.bbloc259.util.ActivityLaunchUtils;
import com.kidback.bbloc259.util.GsonUtils;
import com.kidback.bbloc259.util.LogUtils;
import com.kidback.bbloc259.util.StringUtils;
import com.kidback.bbloc259.util.TipUtils;
import com.mylhyl.circledialog.BaseCircleDialog;
import com.mylhyl.circledialog.CircleDialog;
import com.mylhyl.circledialog.view.listener.OnButtonClickListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.net.URLDecoder;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class MineFragment extends BaseFragment<MineFragmentBinding> {

    @Override
    public MineFragmentBinding getViewBinding(ViewGroup container) {
        return MineFragmentBinding.inflate(inflater);
    }

    @Override
    protected void initView() {

        refreshUserInfo();


        viewBinding.tvLoginName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (UserDataProvider.getInst().hasUserData()) {

                } else {
                    ActivityLaunchUtils.launch(getActivity(), LoginActivity.class);
                }
            }
        });

        viewBinding.layoutUnLock.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (1 == 1) {
                    Observable<BaseResponse<String>> observable = BBNetApi.getBBService()
                            .createAlipayOrder(4, "9dbd1fa4-8d57-4953-b1ab-84b84b8d8888");
                    Observer<BaseResponse<String>> observer = new BaseObserver<BaseResponse<String>>() {

                        @Override
                        public void onSubscribe(Disposable d) {
                            super.onSubscribe(d);
                        }

                        @Override
                        public void onSuccess(BaseResponse<String> orderResponse) {
                            TipUtils.hideLoadingFixDialog();

                            LogUtils.e("111", orderResponse.data);
                            payAli(orderResponse.data);
                        }

                        @Override
                        public void onFailure(ResponseThrowable e) {
                            TipUtils.hideLoadingFixDialog();

                            TipUtils.showMsgFixed(KidApplication.getCurrentActivity(), "登录失败\n" + e.getMessage());
                        }
                    };

                    ApiHelper.request(observable, observer);

                    return;
                }

                if (UserDataProvider.getInst().hasUserData()) {
                    new AddFriendDialog().show();
                } else {
                    TipUtils.showMsgFixed(KidApplication.getCompactActivity(), "请先登录");
                }

            }
        });

        viewBinding.layoutService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TipUtils.showMsgFixed(KidApplication.getCompactActivity(), "客服邮箱：\nkidback2024@163.com");
            }
        });

        viewBinding.layoutPrivate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WebViewActivity.start(v.getContext(), "隐私政策", "https://www.kidback.top/BBLocationWeb/%E9%9A%90%E7%A7%81%E6%94%BF%E7%AD%96.html");
            }
        });

        viewBinding.layoutUserProtocol.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WebViewActivity.start(v.getContext(), "用户协议", "https://www.kidback.top/BBLocationWeb/%E7%94%A8%E6%88%B7%E5%8D%8F%E8%AE%AE.html");
            }
        });

    }

    @Override
    protected void loadData() {

    }


    private void refreshUserInfo() {
        if (UserDataProvider.getInst().hasUserData()) {
            viewBinding.tvLoginName.setText(UserDataProvider.getInst().get().nick_name);
            viewBinding.layoutUserType.setVisibility(View.VISIBLE);

            viewBinding.btnLogout.setVisibility(View.VISIBLE);
            viewBinding.btnLogout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    BaseCircleDialog dialog = new CircleDialog.Builder()
                            .setTitle("提示")
                            .setText("确定要退出账号吗？")
                            .setWidth(0.7f)
                            .setNegative("取消", new OnButtonClickListener() {
                                @Override
                                public boolean onClick(View v) {

                                    return true;
                                }
                            })
                            .setPositive("退出", new OnButtonClickListener() {
                                @Override
                                public boolean onClick(View v) {

                                    UserDataProvider.getInst().put(null);
                                    EventBus.getDefault().post(new UserInfoEvent());
                                    return true;
                                }
                            })
                            .show(getChildFragmentManager());

                }
            });

        } else {
            viewBinding.layoutUserType.setVisibility(View.GONE);
            viewBinding.tvLoginName.setText("游客（点击登录）");

            viewBinding.btnLogout.setVisibility(View.GONE);
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(UserInfoEvent object) {

        refreshUserInfo();

    }

    private void payAli(String orderInfo) {
        Observable.just(orderInfo)
                .subscribeOn(Schedulers.io())
                .map(new Function<String, Map<String, String>>() {
                    @Override
                    public Map<String, String> apply(String orderInfo) throws Exception {

                        PayTask alipay = new PayTask(getActivity());
                        Map<String, String> resultMap = alipay.payV2(orderInfo, true);


                        LogUtils.e("222", GsonUtils.toJsonString(resultMap));


                        return resultMap;
                    }
                })
                .flatMap(new Function<Map<String, String>, Observable<BaseResponse<String>>>() {
                    @Override
                    public Observable<BaseResponse<String>> apply(Map<String, String> map) throws Exception {
                        if (map == null) {
                            return Observable.error(new Throwable("支付宝未返回支付结果"));
                        } else if (StringUtils.equals(map.get("resultStatus"), "6001")) {
                            return Observable.error(new Throwable(map.get("memo")));
                        } else if (StringUtils.equals(map.get("resultStatus"), "9000")) {
                            return null;
                        } else {
                            return Observable.error(new Throwable(map.get("memo")));
                        }
                    }
                })
                .doOnNext(new Consumer<BaseResponse<String>>() {
                    @Override
                    public void accept(BaseResponse<String> response) throws Exception {

                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseResponse<String>>() {

                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(BaseResponse<String> response) {
                    }

                    @Override
                    public void onError(Throwable e) {
                        TipUtils.showFail(getActivity(), e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }

                });

    }

}
